/**
 * Created by qunxing.du on 2016/8/15.
 * Copyright 2016 汉威.智慧环保事业部 Limited.
 * All rights reserved.
 */

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.junit.Test;

import java.nio.charset.Charset;

/**
 * tcp测试客户端
 */
public class TcpClient {

    @Test
    public void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(group);
        b.channel(NioSocketChannel.class);
        b.handler(new TcpClientChannelInitializer());
        b.option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 120);
        try {
            ChannelFuture f = b.connect("127.0.0.1", 30003).sync();
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully().sync();
        }

    }

    class TcpClientChannelInitializer extends ChannelInitializer<SocketChannel> {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline()
                    .addLast("client-logging-handler", new LoggingHandler(LogLevel.DEBUG))
                    .addLast("client-decoder-handler", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4))
                    .addLast("server-string-decoder",new StringDecoder())
                    .addLast("server-encoder-hanler",new LengthFieldPrepender(4,false))
                    .addLast("server-string-encoder",new StringEncoder())
                    .addLast(new TcpClientHandler());
        }

    }

    class TcpClientHandler extends ChannelInboundHandlerAdapter {

        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            ctx.writeAndFlush("hello,服务端");
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println(msg);
            if ("true".equals(msg)) {
                ctx.close();
            }
        }

        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            ctx.flush();
        }

        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }
    }


}
